package cn.wolfcode.interceptor;


import cn.wolfcode.annotation.LoginAnnotation;
import cn.wolfcode.cache.IUserInfoRedisService;
import cn.wolfcode.domain.UserInfo;
import cn.wolfcode.util.JsonResult;
import cn.wolfcode.util.RedisKeys;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CheckLoginInterceptor implements HandlerInterceptor{


    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {

        if (!(handler instanceof HandlerMethod)){
            return true;//如果当前访问的方法属于贴了mapping注解的,则放行访问
        }

//        String token = req.getHeader("token");
//        UserInfo user = userInfoRedisService.getUserByToken(token);
//        if(user == null){
//            resp.setContentType("application/json;charset=utf-8");
//            resp.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
//            return false;
//        }
        String token = req.getHeader("token");
        UserInfo user = userInfoRedisService.getUserByToken(token);
        HandlerMethod hm = (HandlerMethod)handler;
        if (hm.hasMethodAnnotation(LoginAnnotation.class)){
                if(user == null){
                resp.setContentType("application/json;charset=utf-8");
                resp.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
                return false;
            }
        }

        return true;
    }
}
